package com.tyc.threalpool;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
    // 记录已提交任务数
    private final AtomicInteger submittedTaskCount = new AtomicInteger(0);

    public CustomThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    @Override
    public void execute(Runnable command) {
        submittedTaskCount.getAndIncrement();
        try {
            super.execute(command);
        } catch (Exception e) {
            // 触发拒绝策略可能产生的异常
            submittedTaskCount.getAndDecrement();
            throw e;
        }
    }


    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        submittedTaskCount.getAndDecrement();
    }

    public int getSubmittedTaskCount(){
        return submittedTaskCount.get();
    }
}
